<template>
  <div class="edit-container">
    <el-form v-loading="formLoading" ref="form" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="商家名称" prop="businessName">
        <el-input v-model="form.businessName" placeholder="商家名称" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input v-model="form.contacts" placeholder="联系人" maxlength="11" class="col"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="联系电话" maxlength="11" class="col"></el-input>
      </el-form-item>
      <el-form-item label="座机号" prop="landlineNumber">
        <el-input v-model="form.landlineNumber" placeholder="座机号" maxlength="11" class="col"></el-input>
      </el-form-item>
      <el-form-item label="门店介绍" prop="storeIntroduction">
        <el-input v-model="form.storeIntroduction" placeholder="门店介绍" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="月销售额（元）" prop="monthlySales">
        <el-input v-model="form.monthlySales" placeholder="月销售额（元）" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="门店面积" prop="area">
        <el-input v-model="form.area" placeholder="门店面积" maxlength="30" class="col"></el-input>
      </el-form-item>

      <el-form-item label="主营业务" prop="type">
        <el-select v-model="form.type" placeholder="请选择" class="col">
          <el-option
              v-for="item in businessTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在区域" prop="areaId">
        <el-cascader class="col"
                     placeholder="可输入地区名称进行搜索"
                     v-model="value"
                     :options="options"
                     clearable
                     :props="{ expandTrigger: 'hover' }"
                     filterable
                     @change="handleChange"></el-cascader>
      </el-form-item>
      <el-form-item label="商家地址" prop="address">{{ form.address }}
        <el-button icon="el-icon-location" size="mini" type="primary" @click="showChoosePosition=true">
          点击选择位置
        </el-button>
      </el-form-item>
      <el-form-item label="详细地址" prop="detailedAddress">
        <el-input v-model="form.detailedAddress" placeholder="详细地址" maxlength="30" class="col"></el-input>
      </el-form-item>
      <el-form-item label="营业时间" prop="startTime">
        <el-time-select
            placeholder="起始时间"
            :picker-options="{
      start: '00:00',
      end: '24:00',
    }"
            v-model="form.startTime" style="margin-right: 8px;width: 176px;">
        </el-time-select>
        <el-time-select
            placeholder="结束时间"
            :picker-options="{
      start: '00:00',
      end: '24:00',
       minTime: form.startTime
    }"
            v-model="form.endTime" style="width: 176px;">
        </el-time-select>
      </el-form-item>
      <el-form-item>
        <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                   @click="handlerSubmit" v-has-permi="['admin:business:save']">保存
        </el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog v-if="showChoosePosition" :close-on-click-modal="false" :close-on-press-escape="false"
               :destroy-on-close="true"
               :visible.sync="showChoosePosition" append-to-body title="选择位置" top="5vh"
               width="40%">
      <iframe v-if="showChoosePosition" id="choosePosition" frameborder=0
              src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=ZILBZ-FEDCL-6M3PO-M7GUW-PXP5T-ABFB4&referer=零工超市"
              style="width: 100%;height: 500px">
      </iframe>
      <span slot="footer" class="dialog-footer">
            <el-button class="primary" type="primary" @click="showChoosePosition = false">确 定</el-button>
          </span>
    </el-dialog>
    <el-dialog
        :visible.sync="uploads.show"
        title="上传封面"
        :append-to-body="true"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px">
      <UploadFile
          v-if="uploads.show"
          :multiple="uploads.multiple"
          @getFile="getFile"
          ref="uploads"
      />
    </el-dialog>
    <el-dialog
        :visible.sync="imgUploads.show"
        title="上传图片"
        :append-to-body="true"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px">
      <UploadFile
          v-if="imgUploads.show"
          :multiple="imgUploads.multiple"
          @getFile="getImage"
          ref="uploads"
      />
    </el-dialog>
  </div>
</template>
<script>
import {detail, save} from "@/api/settle";
import {getBusinessTypeList, optionsList} from "@/api/business";
import {getForm} from "@/utils/utils";
import UploadFile from "@/components/File/UploadFile.vue";

export default {
  components: {UploadFile},
  props: {
    id: {
      default: null
    },
  },
  data() {
    return {
      form: {
        id: null,
        contacts: '',
        phone: '',
        businessName: '',
        address: '',
        latitude: null,
        longitude: null,
        industryIndex: 1,
        isSale: '',
        saleIndex: 1,
        monthlySales: '',
        logo: '',
        startTime: '请选择开始时间',
        endTime: '请选择结束时间',
        businessTime: '',
        area: '',
        detailedAddress: '',
        storeIntroduction: '',
        landlineNumber: '',
        cityId: 0,
        areaId: 0,
        type: ''
      },
      value: [],
      options: [{
        value: '',
        label: '',
        children: [{
          value: '',
          label: '',
          children: [{
            value: '',
            label: ''
          }]
        }]
      }],
      showChoosePosition: false,
      rules: {
        businessName: [{required: true, message: '请填写商家名称', trigger: ['blur']}],
        contacts: [{required: true, message: '请填写联系人', trigger: ['blur']}],
        phone: [{required: true, message: '请填写联系电话', trigger: ['blur']}],
        // landlineNumber: [{required: true, message: '请填写座机号', trigger: ['blur']}],
        storeIntroduction: [{required: true, message: '请填写门店介绍', trigger: ['blur']}],
        monthlySales: [{required: true, message: '请填写月销售额（元）', trigger: ['blur']}],
        area: [{required: true, message: '请填写门店面积', trigger: ['blur']}],
        type: [{required: true, message: '请选择主营业务', trigger: ['blur']}],
        areaId: [{required: true, message: '请选择所在区域', trigger: ['blur']}],
        address: [{required: true, message: '请选择商家地址', trigger: ['blur']}],
        detailedAddress: [{required: true, message: '请填写详细地址', trigger: ['blur']}],
        startTime: [{required: true, message: '请选择起始时间', trigger: ['blur']}],
        endTime: [{required: true, message: '请选择结束时间', trigger: ['blur']}],
      },
      roles: [],
      saveLoading: false,
      formLoading: false,
      uploads: {
        show: false,
        multiple: false,
      },
      typeList: [],
      imageUrl: '',
      imgUploads: {
        show: false,
        multiple: true,
      },
      businessTypeList:[],
    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    this.getOptions()
    this.getBusinessTypeList()
    if (this.id) {
      this.getDetail();
    }
    window.addEventListener('message', (event) => {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        this.form.latitude = loc.latlng.lat;
        this.form.longitude = loc.latlng.lng;
        this.form.address = loc.poiaddress
      }
    }, false);
  },
  methods: {
    getBusinessTypeList(){
      getBusinessTypeList().then(res =>{
        this.businessTypeList = res
      })
    },
    getOptions() {
      optionsList().then(res => {
        this.options = res
      })
    },
    handleChange(value) {
      this.form.value = value
      this.form.areaId = value[2]
      this.form.cityId = value[1]
    },
    getDetail() {
      this.formLoading = true
      detail(this.id).then(res => {
        getForm(res, this.form);
        let arr = this.form.businessTime.split("-")
        this.form.startTime = arr[0]
        this.form.endTime = arr[1]
        this.value = res.value
      }).finally(() => {
        this.formLoading = false;
      })
    },
    getFile(fileList) {
      this.form.businessFace = fileList[0].url
      this.uploads.show = false
    },
    getImage(fileList) {
      this.form.file = fileList
      this.imgUploads.show = false
      let ids = []
      this.form.file.forEach(item => {
        ids.push(item.id)
      })
      this.form.fileId = ids.join(',')
    },
    handlerSubmit() {
      if (this.saveLoading || this.formLoading) {
        return;
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        this.form.businessTime = this.form.startTime + "-" + this.form.endTime
        save(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    close() {
      this.$emit('hideEditDialog')
    }
  }
}
</script>
<style lang="scss" scoped>

.col {
  width: 450px;
}

.img {
  width: 120px;
  height: 120px;
  margin-right: 10px;
}
</style>
